﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects;
using DataObjects.EntityFramework.ModelMapper;
using System.Linq.Dynamic;

namespace DataObjects.EntityFramework.Implementation
{
    public class EntityTrafficTypeDao : ITrafficTypeDao
    {
        public TrafficType GetTrafficType(int TrafficTypeId)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                return Mapper.Map(context.TrafficTypeEntities.FirstOrDefault(t => t.TrafficTypeId == TrafficTypeId));
            }
        }
        public List<TrafficType> GetTrafficType(string sortExpression = "TrafficTypeId ASC")
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var list = new List<TrafficType>();

                var trafficTypes = context.TrafficTypeEntities.AsQueryable().OrderBy(sortExpression).ToList();
                foreach (var trafficType in trafficTypes)
                    list.Add(Mapper.Map(trafficType));

                return list;
            }
        }
        public void InsertTrafficType(TrafficType trafficType)
        {
            var entity = Mapper.Map(trafficType);

            using (var context = DataObjectFactory.CreateContext())
            {
                context.TrafficTypeEntities.AddObject(entity);
                context.SaveChanges();

                // update business object with new version and id
                trafficType.TrafficTypeId = entity.TrafficTypeId;

                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void UpdateTrafficType(TrafficType trafficType)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.TrafficTypeEntities.Where(p => p.TrafficTypeId == trafficType.TrafficTypeId).SingleOrDefault();

                entity.TrafficTypeId = trafficType.TrafficTypeId;
                entity.Description = trafficType.Description;

                context.TrafficTypeEntities.ApplyCurrentValues(entity);
                context.SaveChanges();

                // Update business object with new version
                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void DeleteTrafficType(TrafficType trafficType)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.TrafficTypeEntities.Where(t => t.TrafficTypeId == trafficType.TrafficTypeId).SingleOrDefault();
                context.TrafficTypeEntities.DeleteObject(entity);
                context.SaveChanges();
            }
        }
    }
}
